const express     = require('express');
const app         = express();

// 引入body-parser用于解析post参数
const bodyParser = require('body-parser');

// 需要use的 application/json
app.use(bodyParser.json());
// application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
}));

const constants     = require('./data/constants');
const cacheUtils     = require('./utils/cacheUtils');
const sipServer     = require('./sip/server');
const dbManager     = require('./db/dbmanager');
const settingModel  = require('./model/setting');
const mediaserverModel = require('./model/mediaserver');
const mediaCtrl     = require('./controller/v1/media');
const log4js        = require('./data/log');
const logger        = log4js.getLogger('request');
const scheduleCtrl  = require('./pipe/schedule');
const alertsCtrl    = require('./pipe/alerts');
const adminCtrl     = require('./controller/v1/admin');
const mediaServerCtrl = require('./controller/v1/mediaserver');

// 设置express日志
log4js.useLogger(app,logger);

// express 引入静态资源
app.use(express.static('public'));

// express 引入路由
app.use(require('./routers/mediaserver'));
app.use(require('./routers/service'));
app.use(require('./routers/media'));
app.use(require('./routers/channel'));
app.use(require('./routers/device'));
app.use(require('./routers/admin'));
app.use(require('./routers/setting'));
app.use(require('./routers/alerts'));
app.use(require('./routers/timing'));

process.on('SIGINT', () => {
  logger.info('停止服务，保存临时文件，停止计划任务');
  scheduleCtrl.stop();
  cacheUtils.save(async ()=>{
    dbManager.close();
    process.exit(0);
  });
});

// 捕获异常
// process.on('unhandledRejection', (reason, p) => {
//   logger.error('Unhandled Rejection at:', p, 'reason:', reason);
//   console.trace(p);
// });

//TODO:加载权限管理 https://github.com/OptimalBits/node_acl

/**
 * 启动 http 服务
 */
let server = app.listen(constants.http.port, function () {
  let host = server.address().address;
  let port = server.address().port;
  logger.info(`启动 Web 服务，请打开网址 : http://${host}:${port}`);

  /**从数据库加载配置 */
  dbManager.open();

  // 恢复上次关闭前的设置
  cacheUtils.load(async ()=>{
    // 如果没有管理员信息则新建默认账号
    await adminCtrl.init();
    await mediaServerCtrl.init();
    // 监控ftp文件夹，如果有数据则先处理
    if(alertsCtrl.init()){
      // 监控文件夹，如果有新文件就处理
      alertsCtrl.inspect();
    }
    let sipSetting = await settingModel.load();
    logger.info('加载启动参数:', sipSetting);
    constants.sip.option = sipSetting;

    // 加载 medisServer 信息
    let medias = await mediaserverModel.list(0, 10000);
    logger.info('加载媒体服务器信息', medias);
    let connect = true;

    medias.map((item)=>{
      const alive=true;
      // 下面用来检测媒体服务器是否正常
      // const alive =await mediaCtrl.ping(item.server_id);
      if(alive){
        logger.info(`准备释放 rtp 资源 ${item.server_id}`);
        mediaCtrl.resetRtpServer(item.server_id);
      }else{
        logger.error("无法连接媒体服务器,server: ", item)
        connect = false;
      }
    });

    if(connect){
      scheduleCtrl.start();
      sipServer.start(sipSetting);
    }else{
      logger.info('程序将退出，请检查ZLMediaKit是否正常启动');
      process.exit(0)
    }

  });
});
